// 生成唯一文件名
function generateUniqueFileName(filePath) {
	const tempId = Date.now();
	// 简单拼接生成唯一文件名
	return `${tempId}_${filePath.replace(/[^a-zA-Z0-9]/g, '')}.jpg`;
}

// 封装文件上传和获取临时 URL 的函数
// 封装文件上传和获取临时 URL 的函数

async function uploadAndGetTempUrl(filePath, cloudPath) {
   var progress=0
	try {
	
		const uploadResult = await uniCloud.uploadFile({
			filePath,
			cloudPath,
			   onUploadProgress(progressEvent) {
			        if (!progressEvent.total) return; // 避免total为0导致的NaN
			        progress = Math.round((progressEvent.loaded / progressEvent.total) * 100);
			        // 实时更新toast的标题（每次进度变化都重新调用showToast）
					
			       uni.$emit('update-progress',{title:"上传中",progress:progress})
			      }
		});

		const urlRes = await uniCloud.getTempFileURL({
			fileList: [uploadResult.fileID]
		});
     
		return urlRes.fileList[0];
	} catch (error) {
		// 出现错误时隐藏加载框
  uni.hideToast();
		console.error('上传或获取临时 URL 失败:', error);
		throw error;
	}
}

export const Images = async () => {
	let imagePaths = [];
	let uploadedImageUrls = [];
	try {
		const res = await new Promise((resolve, reject) => {
			uni.chooseMedia({
				count: 9,
				mediaType: ['image'],
				sizeType: ['compressed'],
				//   sourceType: ['camera','album'],
				camera: "back",
				success: (res) => {
					resolve(res);
				},
				fail: (err) => {
					console.error('选择图片失败:', err);
					reject(err);
				}
			});
		});
		console.log("摄像" + JSON.stringify(res));
		imagePaths = res.tempFiles;

		const batchSize = 3;
		const totalImages = imagePaths.length;
		const totalBatches = Math.ceil(totalImages / batchSize);

		for (let i = 0; i < totalBatches; i++) {
			const start = i * batchSize;
			const end = Math.min((i + 1) * batchSize, totalImages);
			const batchPaths = imagePaths.slice(start, end);

			const uploadTasks = batchPaths.map((filePath) => {
				const uniqueFileName = generateUniqueFileName(filePath.tempFilePath);
				const cloudPath = `mediaMsg/${uniqueFileName}`;
				return uploadAndGetTempUrl(filePath.tempFilePath, cloudPath);
			});

			const batchUrls = await Promise.all(uploadTasks);
			uploadedImageUrls = uploadedImageUrls.concat(batchUrls);
			console.log(`第 ${i + 1} 批图片上传完成，获取到的图片地址:`, batchUrls);
		}

		uni.showToast({
			title: '图片上传完成',
			icon: 'success'
		});
		return uploadedImageUrls;
	} catch (e) {
		console.log(e);
		handleError('选择图片失败', e);
		return [];
	}
};

export const Video = async () => {
  let videoPaths = {
    videoPath: "",
    videoPic: ''
  };
  
  try {
    // 检查网络连接
    const networkType = await new Promise(resolve => {
      uni.getNetworkType({
        success: (res) => resolve(res.networkType),
        fail: () => resolve('none')
      });
    });
    
    if (networkType === 'none') {
      throw new Error('无网络连接，请检查网络设置');
    }

    // 选择视频
    const res = await new Promise((resolve, reject) => {
      uni.chooseMedia({
        count: 1,
        mediaType: ['video'],
        maxDuration: 60,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        camera: "back",
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      });
    });

    if (!res || !res.tempFiles || res.tempFiles.length === 0) {
      throw new Error('未获取到视频文件');
    }

    const tempVideo = res.tempFiles[0];
    console.log("选中的视频信息: ", tempVideo);
    
    // 检查视频大小，例如限制100MB以内
    const maxSize = 100 * 1024 * 1024; // 100MB
    if (tempVideo.size > maxSize) {
      throw new Error('视频大小不能超过100MB');
    }

   
    // 生成唯一的云存储路径
    const timestamp = Date.now();
    const randomStr = Math.random().toString(36).substring(2, 10);
    const uniqueId = `${timestamp}_${randomStr}`;

    // 上传视频文件
    if (!tempVideo.tempFilePath) {
      throw new Error('获取视频临时路径失败');
    }
    videoPaths.videoPath = await uploadAndGetTempUrl(
      tempVideo.tempFilePath, 
      `/videoTempFilePath/${uniqueId}.mp4`
    );

    // 上传视频缩略图
    if (tempVideo.thumbTempFilePath) {
      videoPaths.videoPic = await uploadAndGetTempUrl(
        tempVideo.thumbTempFilePath, 
        `/videoTempFilePath/${uniqueId}_thumb.jpg`
      );
    } else {
      console.warn('未获取到视频缩略图');
    }

    console.log("视频和缩略图的临时访问 URL 已获取", videoPaths);
    return {
		code:true,
		videoPath:videoPaths
	} ;
  } catch (error) {
	  handleError('选择或上传视频失败: ' + error.message, error);
	  return{
		  code:false
	  }
  } 
};

function handleError(message, error) {
	let errorMsg = message;
	if (error.code === 'NETWORK_ERROR') {
		errorMsg = '网络错误，请检查网络连接';
	} else if (error.code === 'UPLOAD_FAILED') {
		errorMsg = '上传失败，请稍后重试';
	}
	console.log(errorMsg, error);
	uni.showToast({
		title: '已取消',
		position:'center'
	});
}